//
//  AppDelegate.swift
//  BaseSwift
//
//  Created by ghwang on 2018/9/26.
//  Copyright © 2018年 ghwang. All rights reserved.
//

import UIKit
import IQKeyboardManagerSwift
import EasyNavigation
import Bugly

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate,WXApiDelegate {

    var window: UIWindow?
    var mainViewController: MainViewController?
    var paySuccess:(() -> Void)?
    var wxAuthSuccess:((String) -> Void)?
    var isWXLogin = false
    var backToVC:UIViewController?
    //var splashAd: OSETAdvert?
    var isForgigenExec = false;



    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        

        self.window = UIWindow()
        self.window?.frame = UIScreen.main.bounds
        self.window?.makeKeyAndVisible()
        let config = BuglyConfig()
        //config.debugMode = true
        config.consolelogEnable = true
        config.reportLogLevel = .debug
        Bugly.start(withAppId:"4846814274",config: config)
        
        //初始化SDK广告
        /*OSETManager.configure("D1F62047B664F57A")
        OSETManager.openDebugLog()*/
        
        configNavbar()
        //wx5b840462ab777fcd
        WXApi.registerApp("wx5b840462ab777fcd", universalLink: "https://www.jianshu.com/p/6a25b18577eb/")
        
        ///控制自动键盘功能启用与否
        IQKeyboardManager.shared.enable = true
        ///键盘弹出时，点击背景，键盘收回
        IQKeyboardManager.shared.shouldResignOnTouchOutside = true
        ///隐藏键盘上面的toolBar,默认是开启的
        IQKeyboardManager.shared.enableAutoToolbar = true
        IQKeyboardManager.shared.toolbarDoneBarButtonItemText = "完成"
        IQKeyboardManager.shared.keyboardDistanceFromTextField = 45
        
        let tempvc = UIViewController()
        tempvc.view.backgroundColor = UIColor.white
        self.window?.rootViewController = EasyNavigationController(rootViewController: tempvc)
        startShowMainView()

        //每次启动都展示
        /*let adImgV = UIImageView()
        self.window?.rootViewController?.view.addSubview(adImgV)
         adImgV.frame = CGRect(x: 0, y: 0, width: KScreenWidth, height: 0)
         self.splashAd = (OSETManager.shareInstance().loadSplashAD(self.window!, bottomView: adImgV, advertId: "D4D9CCA5CE52DC5150D657098F0E7857") as! OSETAdvert)
         self.splashAd?.delegate = self*/
        
        /*if SPUtil.init().firstLaunch == nil {
            


        }
        
        let secs = Date().timeIntervalSince1970 - SPUtil.init().backgroundTimes
        print("timeinter====\(secs)")

        if  secs > 2{ //大于一个小时了
            
            let adImgV = UIImageView()
            adImgV.frame = CGRect(x: 0, y: 0, width: KScreenWidth, height: KScreenHeight)
            self.window?.rootViewController?.view.addSubview(adImgV)
            self.splashAd = (OSETManager.shareInstance().loadSplashAD(self.window!, bottomView: adImgV, advertId: "D4D9CCA5CE52DC5150D657098F0E7857") as! OSETAdvert)
            self.splashAd?.delegate = self
 
        }else{
         
            self.startShowMainView()
            
        }*/

        //self.startShowMainView()

        return true
    }
    //广告加载完调用的方法
    func startShowMainView(){
        
        
        if SPUtil.init().firstLaunch == nil {
            

            let url = URL(fileURLWithPath: Bundle.main.path(forResource: "welcom", ofType: "mov")!)
            let guideView = HHGuidePageHUD.init(videoURL: url,isHiddenSkipButton: false)
            guideView.skipClick = {
                
                guideView.playerCtrl?.player?.pause()
                self.initMainVC()
                SPUtil.init().firstLaunch = "1"

            }

            self.window?.rootViewController?.view.addSubview(guideView)
            
        }else{
            
            self.initMainVC()

        }
        self.getActivis()

        
    }
    /*//广告加载完毕
    func adDidReceiveSuccess(_ advertId: String, handleTarget target: Any) {
        print("广告加载完成")
    }
    //点击广告
    func adClick(_ advertId: String) {
        
    }
    
    //广告关闭
    func adClose(_ advertId: String) {
        
        if self.isForgigenExec == false {
            
            self.startShowMainView()

        }

        print("广告关闭")
    }
    //广告加载失败
    func adDidReceiveLoadFailure(_ errorCode: String, advertId: String, message errorMsg: String) {
        
        print("广告加载失败")
        if self.isForgigenExec == false {
            
            self.startShowMainView()

        }
    }*/
    

    func getActivis(){
        
        API.activityProducts(params: [:]) { (result) in
            
            let arr = (result as! Array<ActivisProduct>)
            SPUtil.init().activits = arr.toJSONString()
        }
    }

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
        
        SPUtil.init().backgroundTimes = Date().timeIntervalSince1970
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
        /*let secs = Date().timeIntervalSince1970 - SPUtil.init().backgroundTimes
        print("timeinter====\(secs)")
        self.isForgigenExec = true
        if secs > 3600{ //大于一个小时了
            
            let adImgV = UIImageView()
            adImgV.frame = CGRect(x: 0, y: 0, width: KScreenWidth, height: 0)
            self.splashAd = (OSETManager.shareInstance().loadSplashAD(self.window!, bottomView: adImgV, advertId: "D4D9CCA5CE52DC5150D657098F0E7857") as! OSETAdvert)
            self.splashAd?.delegate = self
            
        }*/
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }
    
    //显示主界面
    @objc func  initMainVC(){
        
        
        self.window?.rootViewController = EasyNavigationController(rootViewController: HomeViewController())
    
    }
    

    
    func configNavbar() {
        
        let options = EasyNavigationOptions.shareInstance()
        options?.titleColor = UIColor.black
        options?.buttonTitleFont = UIFont.systemFont(ofSize: 18)
        options?.buttonTitleColor = UIColor.black
        options?.navBackGroundColor = UIColor.white
        options?.backGroundAlpha = 1
        options?.navLineColor = UIColor.clear
        options?.navigationBackButtonImage = UIImage(named:"nav_back")
        
    }
    
    func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
        
        
        AlipaySDK.defaultService()?.processOrder(withPaymentResult: url, standbyCallback: { (dic) in
            
            if (dic!["resultStatus"] as! String) == "9000"{
                
                //支付成功
                self.paySuccess!()
                
            }else{
                
                ToastUtil.show(msg: "用户主动取消支付")
            }
        })
        
        WXApi.handleOpen(url, delegate: self)
        return  true
    }
    func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
        return WXApi.handleOpenUniversalLink(userActivity, delegate: self)
    }
    
    func onResp(_ resp: BaseResp!) {
        
        if resp as? PayResp != nil{
            
            if resp.errCode == 0{
                
                //支付成功
                
                self.paySuccess!()
                
            }else if resp.errCode == -1{
                
                ToastUtil.showHUDError(msg: "签名错误")
            }else if resp.errCode == -2{
                
                ToastUtil.showHUDError(msg: "用户主动取消支付")
            }
        }
        
        if resp as? SendAuthResp != nil {
            
            let auth = resp as! SendAuthResp
            if auth.errCode != 0 {
                
                ToastUtil.show(msg: "微信登录授权失败")
                
            }else{
                
                self.wxAuthSuccess!(auth.code!)
                
            }

        }
    }
    
    deinit {
        
        /// 移除通知
        NotificationCenter.default.removeObserver(self)
    }
}


